<template>
	<view class="cart">
		<view class="cart_content">
			<view class="cart_card" v-if="data.product.length">
				<view class="cart_content">
					<view class="cart_content_card" v-for="(item, index) in data.product" :key="item.id">
						<view class="cart_content_left">
							<view class="cart_content_check">
								<checkbox :checked="item.ischecked" :value="String(item.id)" shape="circle" active-color="#ed7b49" @click="checkboxChange(item)"></checkbox>
							</view>
							<view class="cart_content_img">
								<image :src="item.image_url" mode="aspectFit"></image>
							</view>
						</view>
						<view class="cart_content_right">
							<view class="cart_content_right_top">
								<view class="cart_content_title">{{ item.product_name }}</view>
								<view class="cart_content_description">
									<up-text :lines="2" :text="item.description" color="#878787"></up-text>
								</view>
							</view>
							<view class="cart_content_right_bottom">
								<view class="cart_content_right_price">￥{{ calculatePrice(item) }}</view>
								<view class="cart_content_right_number">
									<up-number-box v-model="item.quantity" min="1" :max="item.inventory" color="black" bg-color="#fa8a59" button-size="25" @change="changeNum(item)"></up-number-box>
								</view>
							</view>
						</view>
					</view>
				</view>

				<view class="cart_bottom"></view>
			</view>
			<view class="cart_card_full" v-else>
				<up-empty mode="car" icon="http://cdn.uviewui.com/uview/empty/car.png"></up-empty>
			</view>
			<view class="content">
				<view class="cart_submit_left">
					<view class="cart_submit_check">
						<checkbox :checked="checked" shape="circle" active-color="#ed7b49" @click="toggleAllCheck">全选</checkbox>
						<view class="cart_submit_font" @click="deleteShopping">删除</view>
					</view>
				</view>
				<view class="cart_submit_right">
					<view class="cart_submit_right_font">合计:￥{{ totalPrice }}</view>
					<view class="cart_submit_right_button">
						<view @click="submitOrder">
							<up-button text="提交订单" shape="circle" color="#ed7b49"></up-button>
						</view>
					</view>
				</view>
			</view>
			<up-toast ref="uToastRef"></up-toast>
		</view>
	</view>
</template>

<script setup>
import cartCardVue from '../../components/cartCard/cartCard.vue';
import cartSubmitVue from '../../components/cartSubmit/cartSubmit.vue';
import { GetShoppingCart, DeleteShoppingData, ChangeQuantityInShopping } from '../../apis/api.js';
import { watch, reactive, ref, watchEffect, onMounted, computed } from 'vue';
import useCartStore from '../../store/index.js';

// 定义一个 checkedItems 数组，用于存储已勾选的商品 ID
const checkedItems = ref([]);

// 定义一个 productId 变量，用于存储商品 ID
const productId = ref();

// 定义全选变量
const checked = ref(false);

// toast
const toast = reactive({
	type: '',
	message: ''
});
// 方法
const uToastRef = ref(null);

const data = reactive({
	user_id: '',
	// shopinngData: []
	product: []
});
const cartStore = useCartStore();

// 通过 id 获取用户信息
watch(() => {
	uni.getStorage({
		key: 'userId',
		success: async (res) => {
			data.user_id = res.data;
			console.log('获取的 userId 为：', data.user_id);
			await GetShoppingCart(data.user_id).then((res) => {
				if (res.msgType == 8000) {
					console.log(res);
					data.shopinngData = res.data;
					cartStore.initBadge(data.user_id);
				}
			});
		},
		fail: (error) => {
			console.error('获取 userId 失败：', error);
		}
	});
});

watch(() => {
	// 购物车的角标
	watchEffect(() => {
		// 这里使用 debounce 函数来防抖，避免频繁更新 badge
		const debouncedUpdateBadge = debounce(() => {
			uni.setTabBarBadge({
				// 显示数字
				index: 2, // tabbar 下标
				pagePath: '/pages/cart/cart', // 页面路径
				text: String(cartStore.$state.badge) // 数字
			});
		}, 500);

		// 初始化 badge
		debouncedUpdateBadge();

		// 监听购物车数据变化
		cartStore.$subscribe((mutation, state) => {
			debouncedUpdateBadge();
		});
	});
});

function getBadge() {
	return cartStore.$state.badge;
}

// 防抖函数
function debounce(callback, delay) {
	let timer;
	return (...args) => {
		clearTimeout(timer);
		timer = setTimeout(() => {
			callback.apply(this, args);
		}, delay);
	};
}

// const refreshData = () => {
// 	cartStore.initBadge(data.user_id);
// };

// 获取购物车数据的函数
const getShoppingCartData = async (userId) => {
	await GetShoppingCart(userId).then((res) => {
		if (res.msgType == 8000) {
			console.log(res);
			data.product = res.data;
		}
	});
};

// 通过 id 获取用户信息
watchEffect(() => {
	uni.getStorage({
		key: 'userId',
		success: async (res) => {
			data.user_id = res.data;
			console.log('获取的 userId 为：', data.user_id);
			getShoppingCartData(data.user_id);
			getBadge();
		},
		fail: (error) => {
			console.error('获取 userId 失败：', error);
		}
	});
});

// 抛出事件，当子组件的数据修改时,让父组件取刷新
// const emits = defineEmits(['refreshData']);

// 计算总金额
// 计算总金额
const totalPrice = computed(() => {
	let sum = 0;
	data.product.forEach((item) => {
		if (item.ischecked) {
			sum += parseFloat(item.price * item.quantity);
		}
	});
	return sum.toFixed(2);
});

// 计算单个商品的金额
function calculatePrice(item) {
	return (item.price * item.quantity).toFixed(2);
}

// 勾选/取消勾选商品
const checkboxChange = (item) => {
	const i = data.product.findIndex((value) => value.id === item.id);
	data.product[i].ischecked = !data.product[i].ischecked;
	const allChecked = data.product.every((v) => v.ischecked);
	if (allChecked) {
		checked.value = true;
	} else {
		checked.value = false;
	}
	// 当商品被选中时，它将其 ID 添加到 checkedItems 数组中；当商品被取消选中时，它将从数组中移除其 ID
	if (data.product[i].ischecked) {
		checkedItems.value.push(item.id);
	} else {
		const index = checkedItems.value.indexOf(item.id);
		if (index !== -1) {
			checkedItems.value.splice(index, 1);
		}
	}
};

// 全选/取消全选
function toggleAllCheck(e) {
	// 第一次点击全选时，将 checked 的值取反，并选中或取消选中所有商品
	if (!checked.value) {
		checked.value = true;
		data.product.forEach((v) => {
			v.ischecked = true;
			if (!checkedItems.value.includes(v.id)) {
				checkedItems.value.push(v.id);
			}
		});
	} else {
		checked.value = false;
		// 取消选中所有商品，并清空 checkedItems 数组
		data.product.forEach((v) => {
			v.ischecked = false;
		});
		checkedItems.value = [];
	}
}

// 修改数量
const changeNum = (item) => {
	console.log(item);
	watch(item,(newVal,oldVal)=>{
		// console.log(newVal);
		 ChangeQuantityInShopping({
			quantity: newVal.quantity, 
			id: newVal.id
		}).then((res) => {
			console.log(res);
			if (res.msgType == 8000) {
				toast.type = 'loading';
				toast.message = res.msg;
				uToastRef.value.show({ type: toast.type, message: toast.message, duration: 500 });
			} else {
				toast.type = 'error';
				toast.message = res.msg;
				uToastRef.value.show({ type: toast.type, message: toast.message, duration: 500 });
			}
		});
	})
};

// 定义一个 computed 属性，用于判断是否所有商品都被勾选
const allChecked = computed(() => {
	return data.product.every((item) => item.ischecked);
});

// 删除购物车
const deleteShopping = () => {
	if (checkedItems.value.length > 0) {
		// 先保存当前选中的商品列表
		const selectedItems = checkedItems.value.slice();
		// 弹出确认框
		uni.showModal({
			title: '确认删除',
			content: '确定要删除选中的商品吗？',
			success: function (res) {
				if (res.confirm) {
					// 用户点击确定执行删除操作
					// 获取要删除的商品的 ID
					const deleteIds = selectedItems;
					DeleteShoppingData({
						id: deleteIds
					}).then((res) => {
						// 删除成功后更新数据
						if (res.msgType == 8000) {
							toast.type = 'success';
							toast.message = res.msg;
							uToastRef.value.show({ type: toast.type, message: toast.message, duration: 300 });
							getShoppingCartData(data.user_id);
							cartStore.initBadge(data.user_id);
							// 删除成功后更新选中状态和全选状态
							data.product.forEach((item) => {
								if (selectedItems.includes(item.id)) {
									item.ischecked = false;
								}
							});
							checkedItems.value = checkedItems.value.filter((id) => !selectedItems.includes(id));
							checked.value = allChecked.value;
						} else {
							toast.type = 'error';
							toast.message = res.msg;
							uToastRef.value.show({ type: toast.type, message: toast.message, duration: 300 });
						}
					});
				}
			}
		});
		// getBadge();
	} else {
		toast.type = 'error';
		toast.message = '请选择要删除的商品';
		uToastRef.value.show({ type: toast.type, message: toast.message, duration: 300 });
	}
};

// 提交订单
const submitOrder = () => {
	console.log(checkedItems.value);
	if (checkedItems.value.length > 0) {
		uni.navigateTo({
			url: '/pages/submitOrder/submitOrder?id=' + JSON.stringify(checkedItems.value)
		});
	} else {
		// 显示没有选中商品的提示信息
		uni.showToast({
			title: '请选择商品',
			icon: 'none'
		});
	}
};
</script>

<style lang="less" scoped>
.cart {
	width: 100%;
	height: 100vh;
	background-color: #f5f9fa;
}
.cart_card {
	width: 100%;
	background-color: #f5f9fa;
	box-sizing: border-box;
	padding: 10rpx;
	.cart_content {
		.cart_content_card {
			width: 100%;
			height: 250rpx;
			border: 2rpx solid #ccc;
			border-radius: 5px;
			box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08);
			margin-bottom: 10rpx;
			background-color: #ffffff;
			display: flex;
			.cart_content_left {
				width: 40%;
				display: flex;
				justify-content: center;
				align-items: center;
				padding: 10rpx;
				.cart_content_img {
					width: 200rpx;
					height: 200rpx;
					image {
						width: 100%;
						height: 100%;
					}
				}
			}
			.cart_content_right {
				width: 60%;
				padding: 20rpx;
				.cart_content_right_top {
					.cart_content_title {
						padding: 6rpx;
					}
				}
				.cart_content_right_bottom {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-top: 30rpx;
					.cart_content_right_price {
						color: #fa8a59;
						font-size: 36rpx;
					}
					.cart_content_right_number {
					}
				}
			}
		}
	}
}
.content {
	width: 100%;
	height: 100rpx;
	position: fixed;
	bottom: 80rpx;
	// #ifndef H5
	bottom: 5rpx;
	// #endif
	border: 2rpx solid #ccc;
	border-radius: 5px;
	box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
	// margin-bottom: 10rpx;
	display: flex;
	justify-content: space-between;
	background-color: #f9f9f9;
	z-index: 1;
	.cart_submit_left {
		width: 40%;
		// border: 1px solid red;
		.cart_submit_check {
			display: flex;
			justify-content: center;
			align-items: center;
			margin-top: 30rpx;
			.cart_submit_font {
				margin-left: 50rpx;
				color: red;
			}
		}
	}
	.cart_submit_right {
		display: flex;
		justify-content: center;
		align-items: center;
	}
}
</style>
